import os
import json
import hashlib
import re
import threading
from urllib.parse import urlparse
import shutil

_pro_dir = os.getcwd()
common_download_dir = os.path.join(_pro_dir, 'download')
common_mission_cache_dir = None  # 任务的缓存
common_mission_cache_recode_path = None  # 记录下载的
_common_cache_mission = None

lock = threading.Lock()
_mission_queue = []


def common_SetCommonCacheMission(common_cache_mission):
    global _common_cache_mission
    _common_cache_mission = common_cache_mission


def common_GetCommonCacheMission():
    return _common_cache_mission


def common_ParseUrl(url: str):
    # 解析 URL
    parsed_url = urlparse(url)
    # 提取主机名和路径
    host = parsed_url.hostname
    path = parsed_url.path
    return host, path


def common_IsUrl(input_str):
    # 定义链接的正则表达式模式
    url_pattern = re.compile(r'^(http://|https://|ftp://|www\.)')

    # 使用正则表达式匹配字符串
    return bool(url_pattern.match(input_str))


def common_Md5Str(content: str) -> str:
    """MD5计算

    Args:
        content (str): 内容

    Returns:
        _type_: 返回MD5字符串
    """
    md5_hash = hashlib.md5(content.encode()).hexdigest()
    return md5_hash


def common_CacheDir(path: str) -> str:
    global common_mission_cache_dir
    if common_mission_cache_dir is None:
        path_name = path.replace('/', '').replace('.', '')
        common_mission_cache_dir = os.path.join(_pro_dir, f'cache\{path_name}')
        if not os.path.exists(common_mission_cache_dir):
            os.makedirs(common_mission_cache_dir)
    return common_mission_cache_dir


def common_CacheFilePath(path: str) -> str:
    global common_mission_cache_recode_path
    if common_mission_cache_recode_path is None:
        cache_dir = common_CacheDir(path=path)
        common_mission_cache_recode_path = os.path.join(cache_dir, 'cache.txt')
    return common_mission_cache_recode_path


def common_CacheRecode(path: str) -> dict | None:
    """读取缓存内容

    Args:
        path (str): 文件的名字

    Returns:
        _type_: 读取的内容
    """
    file_path = common_CacheFilePath(path=path)
    if os.path.exists(file_path):
        with open(file=file_path, mode='r', encoding='utf-8') as f:
            content = f.read()
            if len(content) > 0:
                return json.loads(content)
            else:
                return None
    else:
        return None


def common_DeleteAllCache(path: str):
    """删除缓存文件夹

    Args:
        path (str): 文件的名字
    """
    cache_dir = common_CacheDir(path=path)
    try:
        shutil.rmtree(cache_dir)
        print(f"删除成功 '{cache_dir}'")
    except Exception as e:
        print(f"删除失败 '{cache_dir}': {e}")


def common_CacheTsPath(path: str):
    cache_dir = common_CacheDir(path=path)
    path_name = path.replace('/', '')
    file_path = os.path.join(cache_dir, f'{path_name}')
    return file_path


def common_CacheM3u8FilePath(path: str):
    cache_dir = common_CacheDir(path=path)
    file_path = os.path.join(cache_dir, f'index.m3u8')
    return file_path


def common_EncryKeyFilePath(path: str):
    cache_dir = common_CacheDir(path=path)
    file_path = os.path.join(cache_dir, f'key.txt')
    return file_path


def common_AddMission(mission: dict):
    """添加任务

    Args:
        mission (dict): 
    """
    with lock:
        global _mission_queue
        _mission_queue.append(mission)


def common_GetMission():
    """获取任务

    Returns:
        _type_: _description_
    """
    with lock:
        global _mission_queue
        if len(_mission_queue) > 0:
            return _mission_queue.pop(0), len(_mission_queue)
        else:
            return None, 0


def common_DownloadPath(file_name: str):
    if not os.path.exists(common_download_dir):
        os.makedirs(common_download_dir)

    return os.path.join(common_download_dir, file_name)


def common_SaveCache(content: any, mission: dict):
    """保存缓存

    Args:
        path (str): 文件地址
        content (any): ts 下载内容
        mission (dict): ts 任务
    """
    with lock:
        ts_path = mission['file_path']
        with open(ts_path, 'wb') as f:
            f.write(content)

        # 更新缓存记录
        datas = _common_cache_mission['data']
        for data in datas:
            if mission['url'] == data['url']:
                data['is_done'] = True

        cache_mission_str = json.dumps(_common_cache_mission)
        # 到这里肯定是已经有了的
        global common_mission_cache_recode_path
        if common_mission_cache_recode_path == None:
            print('这里不应该是空的')
        with open(file=common_mission_cache_recode_path, mode='w', encoding='utf-8') as f:
            f.write(cache_mission_str)
